package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.DateConversionUtils;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.FreezeApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.Comment;
import com.tanhua.model.db.Freeze;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @auther : 白月尘
 * @date : 16:40  2021/10/21
 */
@Service
public class CommentsService {
    @DubboReference
    private CommentApi commentApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private MqMessageService mqMessageService;
    @Autowired
    private RedisTemplate redisTemplate;
    @DubboReference
    private FreezeApi freezeApi;

    public PageResult comments(Integer page, Integer pageSize, String movementId) {
        List<Comment> comment=commentApi.comment(page,pageSize,movementId);
        if (comment==null||comment.size()<=0){
            return new PageResult();
        }
        List<Long> userId = CollUtil.getFieldValues(comment, "userId", long.class);
        Map<Long, UserInfo> all = userInfoApi.findAll(userId);
        List<CommentVo> commentVos=new ArrayList<>();
        for (Comment comment1 : comment) {
            UserInfo userInfo = all.get(comment1.getUserId());
            CommentVo vo = CommentVo.init(userInfo, comment1);
            commentVos.add(vo);
        }
        return new PageResult(page,pageSize,0l,commentVos);
    }

    public void subComments(Map map) {
        String movementId = map.get("movementId").toString();//动态Id
        String comment = map.get("comment").toString();
        Comment comment1=new Comment();
        comment1.setPublishId(new ObjectId(movementId));
        comment1.setContent(comment);
        comment1.setCreated(System.currentTimeMillis());
        comment1.setCommentType(2);
        comment1.setUserId(UserHolder.getUserId());
        Integer i=commentApi.save(comment1);
        System.out.println("评论数为"+i);
        mqMessageService.sendLogService(UserHolder.getUserId(),"0205","movement",movementId);
    }

    public Integer like(String id) {
        boolean hasComment = commentApi.hasComment(id, UserHolder.getUserId(), 1);
        if (hasComment) {
            throw new BusinessException(ErrorResult.likeError());
        }
        //调用API保存互动数据
        Comment comment1 = new Comment();
        comment1.setPublishId(new ObjectId(id));
        comment1.setCreated(System.currentTimeMillis());
        comment1.setCommentType(1);
        comment1.setUserId(UserHolder.getUserId());
        Integer i = commentApi.saveCommentLike(comment1);
        //在redis中记录点赞状态
        String redisKey = Constants.MOVEMENTS_INTERACT_KEY + id;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(redisKey, hashKey, "1");
        mqMessageService.sendLogService(UserHolder.getUserId(),"0203","movement",id);
        return i;
    }

    public Integer dislike(String id) {
        //判断是否点赞
        boolean hasComment = commentApi.hasComment(id, UserHolder.getUserId(), 1);
        //1.查询是否已经点赞,如果已点赞抛出异常
        if (!hasComment) {
            //2.如果未点赞,抛出异常
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //3.如果已点赞,删除mongo数据,redis数据
        Integer i = commentApi.deleteCommentLike(id, UserHolder.getUserId(), 1);
        String redisKey = Constants.MOVEMENTS_INTERACT_KEY + id;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(redisKey, hashKey);
        mqMessageService.sendLogService(UserHolder.getUserId(),"0206","movement",id);
        return i;
    }

    public void checkFreezeState(Long userId, Map map) {
        Freeze freeze = freezeApi.selectByUid(userId);
        if (freeze == null) {
            this.subComments(map);
        }
        // 冻结范围：1为冻结登录，2为冻结发言，3为冻结发布动态
        if (freeze != null && freeze.getFreezingRange() == 2) {
            Date currentDate = DateConversionUtils.parseStrToDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                    .format(new Date()), "yyyy-MM-dd HH:mm:ss", new Date());
            Date unfreezeTime = freeze.getUnfreezeTime();
            Long timeDifference = freezeApi.selectFreezeTimeDifference(currentDate, unfreezeTime);
            if (timeDifference <= 0) {
                //已到解封时间
                freeze.setIsFreezing(1);//1解冻，2冻结
                freeze.setReasonsForThawing(DateUtil.now()+"到期自动解冻~");
                freezeApi.updateById(freeze);
                this.subComments(map);
            } else {
                //当前用户被冻结
                throw new BusinessException(ErrorResult.FreezeCommentError(freeze.getUnfreezeTime()));
            }
        }
    }
}
